package com.macro.mall.controller;

import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.config.XhsApiConfig;
import com.macro.mall.dto.XhsOrderDetailVO;
import com.macro.mall.dto.XhsOrderQueryParam;
import com.macro.mall.dto.XhsOrderVO;
import com.macro.mall.model.XhsOrder;
import com.macro.mall.model.request.VoucherVerifyRequest;
import com.macro.mall.model.request.order.CreateOrderRequest;
import com.macro.mall.model.response.OrderUpsertResponse;
import com.macro.mall.model.response.VoucherVerifyResponse;
import com.macro.mall.service.XhsLoginService;
import com.macro.mall.service.XhsOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Controller
@Api(tags = "XHSOrderController")
@Tag(name = "XHSOrderController", description = "小红书订单管理")
@RequestMapping("/xhsorder")
public class XHSOrderController {

    @Resource
    private XhsOrderService xhsOrderService;

    @Resource
    private XhsLoginService xhsLoginService;



    @Resource
    private XhsApiConfig xhsApiConfig;

    // 从配置文件中读取参数（建议放在application.yml/properties）
    @Value("${xhs.app-id}")
    private String APP_ID;

    @Value("${xhs.access-token}")
    private String ACCESS_TOKEN;

    @Resource
    private OkHttpClient okHttpClient;


    /**
     * 创建小红书订单
     */
    @PostMapping("/create")
    public OrderUpsertResponse createOrder(@RequestBody CreateOrderRequest request) {
        OrderUpsertResponse order = xhsOrderService.createOrder(request);
        return order;
    }

    /**
     * 获取订单详情
     */
    @GetMapping("/detail/{id}")
    public XhsOrder getOrderDetail(@PathVariable Long id) {
        XhsOrder order = xhsOrderService.getOrderById(id);
        return order;
    }

    /**
     * 根据外部订单ID获取订单
     */
    @GetMapping("/out/{outOrderId}")
    public XhsOrder getOrderByOutOrderId(@PathVariable String outOrderId) {
        XhsOrder order = xhsOrderService.getOrderByOutOrderId(outOrderId);
        return order;
    }

    /**
     * 获取用户订单列表
     */
    @GetMapping("/user/{openId}")
    public List<XhsOrder> getUserOrders(@PathVariable String openId) {
        List<XhsOrder> orders = xhsOrderService.getUserOrders(openId);
        return orders;
    }

    /**
     * 更新订单状态
     */
    @PostMapping("/updateStatus")
    public Boolean updateOrderStatus(@RequestParam Long id,
                                             @RequestParam Integer orderStatus) {
        boolean success = xhsOrderService.updateOrderStatus(id, orderStatus);
        return success;
    }
    
    // ========== 新增接口：订单列表管理 ==========
    
    /**
     * 分页查询小红书订单列表
     */
    @ApiOperation("分页查询小红书订单列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<XhsOrderVO>> list(
            XhsOrderQueryParam queryParam,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        
        try {
            // 添加调试日志
            System.out.println("收到订单列表请求，参数：" + queryParam);
            System.out.println("分页参数：pageNum=" + pageNum + ", pageSize=" + pageSize);
            
            CommonPage<XhsOrderVO> orderList = xhsOrderService.getOrderList(queryParam, pageNum, pageSize);
            System.out.println("查询结果：总数=" + orderList.getTotal() + ", 数据条数=" + orderList.getList().size());
            
            return CommonResult.success(orderList);
        } catch (Exception e) {
            System.err.println("订单列表查询失败：" + e.getMessage());
            e.printStackTrace();
            return CommonResult.failed("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情（管理端）
     */
    @ApiOperation("获取小红书订单详情")
    @RequestMapping(value = "/admin/detail/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<XhsOrderDetailVO> getAdminDetail(@PathVariable Long id) {
        XhsOrderDetailVO orderDetail = xhsOrderService.getOrderDetail(id);
        if (orderDetail == null) {
            return CommonResult.failed("订单不存在");
        }
        return CommonResult.success(orderDetail);
    }
    
    /**
     * 批量删除订单
     */
    @ApiOperation("批量删除订单")
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return CommonResult.validateFailed("订单ID列表不能为空");
        }
        
        boolean success = xhsOrderService.batchDeleteOrders(ids);
        if (success) {
            return CommonResult.success("批量删除成功");
        } else {
            return CommonResult.failed("批量删除失败");
        }
    }
    
    /**
     * 批量关闭订单
     */
    @ApiOperation("批量关闭订单")
    @RequestMapping(value = "/batchClose", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult batchClose(@RequestBody List<Long> ids, 
                                  @RequestParam(required = false, defaultValue = "管理员手动关闭") String reason) {
        if (ids == null || ids.isEmpty()) {
            return CommonResult.validateFailed("订单ID列表不能为空");
        }
        
        boolean success = xhsOrderService.batchCloseOrders(ids, reason);
        if (success) {
            return CommonResult.success("批量关闭成功");
        } else {
            return CommonResult.failed("批量关闭失败");
        }
    }
    
    /**
     * 单个删除订单
     */
    @ApiOperation("删除订单")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult deleteOrder(@PathVariable Long id) {
        List<Long> ids = Arrays.asList(id);
        boolean success = xhsOrderService.batchDeleteOrders(ids);
        if (success) {
            return CommonResult.success("删除成功");
        } else {
            return CommonResult.failed("删除失败");
        }
    }
    
    /**
     * 单个关闭订单
     */
    @ApiOperation("关闭订单")
    @RequestMapping(value = "/close/{id}", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult closeOrder(@PathVariable Long id, 
                                  @RequestParam(required = false, defaultValue = "管理员手动关闭") String reason) {
        List<Long> ids = Arrays.asList(id);
        boolean success = xhsOrderService.batchCloseOrders(ids, reason);
        if (success) {
            return CommonResult.success("关闭成功");
        } else {
            return CommonResult.failed("关闭失败");
        }
    }

//    /**
//     * 分页查询订单
//     */
//    @GetMapping("/list")
//    public Result<PageResult<XhsOrder>> getOrderList(
//            @RequestParam(required = false) Long startTime,
//            @RequestParam(required = false) Long endTime,
//            @RequestParam(required = false) Integer orderStatus,
//            @RequestParam(defaultValue = "1") Integer pageNum,
//            @RequestParam(defaultValue = "10") Integer pageSize) {
//
//        Date startDate = startTime != null ? new Date(startTime) : null;
//        Date endDate = endTime != null ? new Date(endTime) : null;
//
//        List<XhsOrder> list = xhsOrderService.getOrderList(
//                startDate, endDate, orderStatus, pageNum, pageSize);
//
//        int total = xhsOrderService.countOrderList(startDate, endDate, orderStatus);
//
//        PageResult<XhsOrder> pageResult = new PageResult<>();
//        pageResult.setList(list);
//        pageResult.setTotal(total);
//        pageResult.setPageNum(pageNum);
//        pageResult.setPageSize(pageSize);
//
//        return Result.success(pageResult);
//    }


















    @GetMapping("/xhs/login")
    public XhsLoginController.XhsResponse login(@RequestParam String code) {
        // 构建请求URL
        HttpUrl url = HttpUrl.parse(xhsApiConfig.getBaseUrl() + "/api/rmp/session").newBuilder()
                .addQueryParameter("app_id", APP_ID)
                .addQueryParameter("access_token", ACCESS_TOKEN)
                .addQueryParameter("code", code)
                .build();

        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                return handleErrorResponse(response);
            }

            // 解析响应
            okhttp3.ResponseBody body = response.body();
            if (body != null) {
                // 实际实现需要完整的JSON解析
                // 这里使用简化示例，建议使用Jackson完整解析
                String responseBody = body.string();
                return parseResponse(responseBody);
            }
            return new XhsLoginController.XhsResponse(false, "Empty response", -1, null);
        } catch (IOException e) {
            return new XhsLoginController.XhsResponse(false, "API request failed: " + e.getMessage(), -500, null);
        }
    }




    // 解析响应（需要根据实际响应结构调整）
    private XhsLoginController.XhsResponse parseResponse(String responseBody) {
        // 实际实现应使用JSON解析库（如Jackson）
        // 这里演示基本结构，建议创建完整的DTO类
        if (responseBody.contains("\"code\":0")) {
            return new XhsLoginController.XhsResponse(true, "success", 0, new XhsLoginController.XhsData("openid_demo", "session_key_demo"));
        }
        return new XhsLoginController.XhsResponse(false, "Unknown error", -1, null);
    }

    private XhsLoginController.XhsResponse handleErrorResponse(Response response) {
        return new XhsLoginController.XhsResponse(false,
                "API Error: " + response.message(),
                response.code(),
                null);
    }

    // 响应DTO
    @Data
    static class XhsResponse {
        private Boolean success;
        private String msg;
        private Integer code;
        private XhsLoginController.XhsData data;

        public XhsResponse(boolean success, String msg, Integer code, XhsLoginController.XhsData data) {
            this.success = success;
            this.msg = msg;
            this.code = code;
            this.data = data;
        }
    }

    @Data
    static class XhsData {
        private String openid;
        private String session_key;

        public XhsData(String openid, String session_key) {
            this.openid = openid;
            this.session_key = session_key;
        }
    }



}
